package cn.gzdf.sboot02.controller;


import cn.gzdf.sboot02.entity.User;
import cn.gzdf.sboot02.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
       //快速打印方法参数的快捷键  soutp
        System.out.println("user = " + user);
        try {
            String sql = "select id from jt_user where username=?";
            Connection conn = DBUtils.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                return "用户名已存在";
            }
            String insertSql = "insert into jt_user values(null,?,?,?,?)";
            PreparedStatement insertPs = conn.prepareStatement(insertSql);
            insertPs.setString(1, user.getUsername());
            insertPs.setString(2, user.getPassword());
            insertPs.setString(3,user.getNick());
            insertPs.setInt(4,user.getAge());
            insertPs.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
            return "注册失败";
        }
        return "注册成功！";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);
        try {
            Connection conn = DBUtils.getConn();//获取连接
            String sql = "select password from jt_user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String pwd = rs.getString(1);
                if(pwd.equals(user.getPassword())){
                    return "登录成功";
                }else {
                    return "密码错误";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "用户名不存在";
    }


}
